﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace UpdateSql
{
    public class DBHelper
    {
        private static void PrepareCommand(string sql, IDbCommand cmd, IDbConnection con, CommandType ct, params IDataParameter[] parms)
        {
            if (con.State != ConnectionState.Open)
            {
                con.Open();
            }
            cmd.CommandText = sql;
            cmd.Connection = con;
            cmd.CommandType = ct;
            foreach (var item in parms)
            {
                cmd.Parameters.Add(item);
            }
        }

        public static int GetNonQuery(string sql, string conStr, CommandType ct, params SqlParameter[] parms)
        {
            SqlCommand cmd = new SqlCommand();
            using (SqlConnection con = new SqlConnection(conStr))
            {
                PrepareCommand(sql, cmd, con, ct, parms);
                return cmd.ExecuteNonQuery();
            }
        }

        public static object GetScalar(string sql, string conStr, CommandType ct, params SqlParameter[] parms)
        {
            SqlCommand cmd = new SqlCommand();
            using (SqlConnection con = new SqlConnection(conStr))
            {
                PrepareCommand(sql, cmd, con, ct, parms);
                return cmd.ExecuteScalar();
            }
        }

        public static DataSet GetSet(string sql, string conStr, CommandType ct, params SqlParameter[] parms)
        {
            DataSet ds = new DataSet();
            using (SqlDataAdapter da = new SqlDataAdapter())
            {
                using (SqlConnection con = new SqlConnection(conStr))
                {
                    PrepareCommand(sql, da.SelectCommand = new SqlCommand(), con, ct, parms);
                    da.Fill(ds);
                    return ds;
                }
            }
        }
    }
}
